<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 *
 * 创建时间：2021-11-03 14:48:29
 *
 * 项目：/levfm  -  $  - FormDataHelper.php
 *
 * 作者：{{AUTO GENERATE}}
 */

//此文件使用程序自动生成，下次生成时【不会】覆盖。
//在这里可以补充、完善你的程序逻辑

namespace modules\levfm\table\form\FormData;

use Lev;
use lev\helpers\subTableHelper;
use lev\widgets\inputs\tablesForm;
use modules\levfm\table\form\FormData\_gen\BaseFormData;
use modules\levfm\table\LevfmDatas;
use modules\levfm\table\LevfmDatasChild;
use modules\levfm\table\LevfmFields;
use modules\levfm\table\LevfmForms;
use modules\levfm\widgets\inputs\formatViewDatas;
use modules\levfm\widgets\inputs\inputDataValidation;
use modules\levfm\widgets\inputs\inputsFormWidget;

!defined('INLEV') && exit('Access Denied LEV');

class BaseFormDataMiddle extends BaseFormData
{

    public static $tableName  = '{{%levfm_datas}}';

    public static $formInfo   = null;

    public static $formFields = null;

    public static $inputs     = null;

    public static $setupDesc  = null;

    public static $srhTypes   = null;//分类搜索字段
    public static $uniques    = null;//唯一字段
    public static $totalitem  = null;//统计字段

    public static $closeClassify = [];

    public static $checkData  = true;//管理员审核通过显示

    public static function saveForm($formPre = 'datax', $route = '', $form = null, $upData = null, $upDataForce = null, $opInfo = null)
    {
        if (subTableHelper::createLock(static::$tableName, true)) {
            return Lev::responseMsg(-44044, '抱歉，分表创建中，请稍候重试');
        }
        //return parent::saveForm($formPre, $route, $form, $upData, $upDataForce, $opInfo); // TODO: Change the autogenerated stub
        $upData === null &&
        $upData = Lev::POSTv($formPre);

        $opid = intval(Lev::GPv('opid'));

        $opInfo === null &&
        $opInfo = $opid >0 ? static::setopInfo($opid) : [];

        if ($opInfo) {
            static::$opInfo['datas'] = LevfmDatas::getDatas($opInfo['datas']);
            $upData += $opInfo;
            $upData += static::$opInfo['datas'];
            $upData['settings'] = Lev::getSettings($opInfo['settings']);
        }else {
            unset($upData['id']);
        }

        static::$formInfo['settings'] = Lev::getSettings(static::$formInfo['settings']);
        if (empty(static::$formInfo['settings']['_srhkeyType'])) {
            if (empty($upData['srhkey']) || strlen($upData['srhkey']) < 4) {
                return static::errorMsg2($formPre . '[srhkey]', -4003001, '抱歉，搜索关键词不能少于4个字符');
            }
        }elseif (static::$formInfo['settings']['_srhkeyType'] == '1') {
            $date = date('Ymd', empty($upData['addtime']) ? Lev::$app['timestamp'] : $upData['addtime']);
            if (empty($upData['srhkey'])) {
                $upData['srhkey'] = $date;
            }elseif (stripos($upData['srhkey'], '#') !==0) {
                $upData['srhkey'] = $date.' '.$upData['srhkey'];
            }
        }

        $upData = static::safeColumnsInpus($upData);
        $upData = static::datasValidation($upData);
        if (isset($upData['ErrorInputName'])) {
            $errorMessage = '【'.Lev::arrv([$upData['ErrorInputName'], 'title'], static::$formFields, $upData['ErrorInputName']).'】';
            $upData['errors'] = [$formPre.'['.$upData['ErrorInputName'].']'=>$errorMessage.$upData['message']];
            return $upData;
        }

        $upDataForce !== null && $upData += $upDataForce;

        empty($upData['uid']) && $upData['uid'] = Lev::$app['uid'];

        $upData['formid'] = static::$formInfo['id'];
        $upData['srhkey'] = LevfmDatasChild::setSrhkey($upData['srhkey']);
        $upData['srhtype']= LevfmDatasChild::setSrhtype(static::$srhTypes);
        $upData['uniques']= LevfmDatasChild::setSrhtype(static::$uniques);

        static::$checkData && $upData['status'] = 2;

        $upData['uptime'] = Lev::$app['timestamp'];
        if ($opInfo) {
            $rs = static::saveInputs($upData, ['id'=>$opid]);
        }else {
            $upData['addtime'] = Lev::$app['timestamp'];
            $rs = static::saveInputs($upData, [], true);
            $opid = $upData['id'] = $rs;
        }
        if ($rs) {
            $tourl = $route ? Lev::toReRoute([$route, 'opid'=>$opid, 'setup'=>static::getNextSetup(), 'form'=>$form ?: null]) : '';
            $upData['id'] = $opid;
            !static::$checkData && LevfmDatasChild::saveChild($upData);
            $opInfo || LevfmForms::updateTotalnum(static::formInfo(), 1);

            $param = ['opid'=>$opid, 'tourl'=>$tourl];//, 'upData'=>$upData
            Lev::GPv('notReload') && $param['notReload'] = 1;
            $param['repeat'] = LevfmForms::isTotalitemRepeat(static::$formInfo['settings']);
            return Lev::responseMsg(1, '保存成功', $param);
        }
        return Lev::responseMsg(-2203, '保存失败');
    }

    /**
     * @param $columns
     * @return mixed
     *
     * @see parent::safeColumnsInpus($columns); // TODO: Change the autogenerated stub
     */
    public static function safeColumnsInpus($columns) {
        if ($columns) {
            foreach ($columns as $k => $v) {
                if ($k != 'settings' && !isset(static::$inputs[$k])) unset($columns[$k]);
            }
        }
        return $columns;
    }

    public static function safeColumnsInpusTables($columns, $pre = 'cld__') {
        if ($columns) {
            foreach ($columns as $k => $v) {
                if (!isset(static::$inputs[$k]) && strpos($k, $pre) !== 0) unset($columns[$k]);
            }
        }
        return $columns;
    }

    /**
     * @param $datas
     * @param array $where
     * @param bool $inId
     * @param array $tables
     * @param array $inputs
     * @param bool $formSet
     * @param array $tablesFormData
     * @return mixed
     *
     * @see parent::saveInputs($datas, $where, $inId, $tables, $inputs, $formSet, $tablesFormData);
     * TODO: Change the autogenerated stub
     */
    public static function saveInputs($datas, $where = [], $inId = false, $tables = [], $inputs = [], $formSet = true, $tablesFormData = [])
    {
        !$inputs && $inputs = static::inputs();
        $datas = inputsFormWidget::formatSaveInputsData($datas, $inputs, $tables, $tablesFormData);
        $formSet && (!$where || isset($datas['settings'])) && $datas = static::getFormSettings($datas, $datas['settings']);
        isset($datas['settings']) && $datas['settings'] = Lev::setSettings($datas['settings']);
        $datas = static::safeColumnsGen($datas);
        return static::save($datas, $where, $inId);
    }

    public static function headerHtm()
    {
        //return parent::headerHtm(); // TODO: Change the autogenerated stub
        //return '<tips class="gray inblk scale8">自定义headerHtm：文件位置：'.__DIR__ . '/FormData.php'.'</tips>';
    }

    public static function footerHtm()
    {
        return parent::footerHtm(); // TODO: Change the autogenerated stub
        //return '<tips class="gray inblk scale8">自定义footerHtm</tips>';
    }

    public static function footerFormInnerHtm()
    {
        return parent::footerFormInnerHtm(); // TODO: Change the autogenerated stub
        //return '<tips class="gray inblk scale8">自定义footerFormInnerHtm</tips>';
    }

    public static function formInfo($formid = null) {
        if ($formid !== null) {
            static::$formInfo === null &&
            static::$formInfo = LevfmForms::findOne(['id' => $formid]);
        }
        return static::$formInfo;
    }

    public static function datasValidation($upData)
    {
        $datas = [];
        totalitemHelper::init(static::$formInfo, static::$opInfo);
        foreach (static::$formFields as $v) {
            $data = isset($upData[$v['inputname']]) ? $upData[$v['inputname']] : null;
            $data = inputDataValidation::dataType($data, $v);

            inputDataValidation::errorInputtypeMessage($data, $v, static::$opInfo);
            if (inputDataValidation::$errorMsg) {
                return inputDataValidation::$errorMsg;
            }

            if (isset($upData[$v['inputname']])) {
                if (($ckData = LevfmFields::isSrhtypeField2($v, $data)) !== false) {
                    static::$srhTypes[$v['id']] = $ckData;
                }

                totalitemHelper::total($v, $data);

                unset($upData[$v['inputname']]);
                $datas[$v['inputname']] = $data;
            }

        }

        if ($tables = static::safeColumnsInpusTables(Lev::POSTv('tables'))) {
            is_array($tabDatas = inputsFormWidget::tablesDataFormat($tables, inputsFormWidget::getTablesIntID(static::$formFields))) &&
            $datas = $tabDatas + $datas;
        }
        if ($tablesForm = Lev::POSTv(tablesForm::getFormPre().'__addtr')) {
            is_array($tabDatas = tablesForm::dataFormat(static::safeColumnsInpusTables(Lev::POSTv(tablesForm::getFormPre())), $tablesForm, true)) &&
            $datas = $tabDatas + $datas;
        }

        totalitemHelper::setTotalitem();

        $upData['datas'] = LevfmDatas::setDatas($datas);
        return $upData;
    }

}


class FormData extends BaseFormDataMiddle {

    public static function allColumns()
    {
        return parent::allColumns(); // TODO: Change the autogenerated stub
    }

    public static function safeColumnsInpus($columns)
    {
        return parent::safeColumnsInpus($columns); // TODO: Change the autogenerated stub
    }

    public static function setFormSettings($settings, $result = [])
    {
        return parent::setFormSettings($settings, $result); // TODO: Change the autogenerated stub
    }

    public static function saveInputs($datas, $where = [], $inId = false, $tables = [], $inputs = [], $formSet = true, $tablesFormData = [])
    {
        return parent::saveInputs($datas, $where, $inId, $tables, $inputs, $formSet, $tablesFormData); // TODO: Change the autogenerated stub
    }

    public static function getNextSetup()
    {
        return parent::getNextSetup(); // TODO: Change the autogenerated stub
    }

    public static function inputsSetup()
    {
        //return parent::inputsSetup(); // TODO: Change the autogenerated stub
        $inputs = static::inputs();
        $commonInputs = static::commonInputs();
        foreach ($inputs as $v) {
            if (!isset($commonInputs[$v['inputname']])) {
                $classify[$v['classify']][$v['inputname']] = $v;
                static::$setupDesc[$v['classify']] = $v['classify'];
            }
        }
        return $classify;
    }

    /**
     * @return array
     */
    public static function setupDesc()
    {
        //return parent::setupDesc(); // TODO: Change the autogenerated stub
        static $order;
        if (empty($order)) {
            $order = 1;
            $setup = LevfmForms::getSettingsClassify(static::$formInfo['settings']);
            if (isset(static::$setupDesc[0])) {
                unset(static::$setupDesc[0]);
                empty($setup[0]) && $setup[0] = ['id' => 0, 'name' => '0@未分类'];
            }
            foreach ($setup as $v) {
                if (!empty($v['status'])) {
                    static::$closeClassify[$v['id']] = $v['id'];
                    unset(static::$setupDesc[$v['id']]);
                }else {
                    (!$v['id'] || isset(static::$setupDesc[$v['id']])) && static::$setupDesc[$v['id']] = $v['name'];
                }
            }
            static::$setupDesc && ksort(static::$setupDesc);
        }
        return static::$setupDesc;
    }

    public static function inputs($iden = '', $keyfield = '', $classify = null)
    {
        if (static::$inputs === null) {
            static::$inputs = static::formFields();
            static::$inputs+= parent::inputs($iden, $keyfield, $classify); // TODO: Change the autogenerated stub
        }
        return static::$inputs;
    }

    public static function formFields() {
        if (static::$formFields === null) {
            static::$formFields = LevfmFields::findAllKeyInputname(['formid' => static::$formInfo['id'], 'status'=>0], ['displayorder ASC', 'id ASC']);
        }
        return static::$formFields;
    }

    public static function commonInputs() {
        $arr = parent::inputs();
        isset($arr['srhkey']['placeholder']) &&
        $arr['srhkey']['placeholder'] .= '<a class="button button-fill scale7 color-gray getInputSrhkeyBtn wd30 wdmin">点我自动获取</a>';
        return $arr;
    }

    /**
     * 额外的表单字段，不会存入数据库
     * @return array
     */
    public static function extInputs()
    {
        return parent::extInputs(); // TODO: Change the autogenerated stub
    }

}